﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeixinBusiness.Model;
using System.IO;
using WeixinBusiness.Core;

namespace WeixinBusiness
{
    public class MenuCore
    {
        public static List<MenuSetting> GetAll(string xmlUrl, bool isOrderBy = true)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = Common.LoadXml<MenuSetting>(xmlUrl);
            if (isOrderBy)
            {
                //list = list.OrderBy(x => x.ParentId).ThenBy(x => x.Orderby).ToList();
                List<MenuSetting> orderByList = new List<MenuSetting>();
                var groups = list.GroupBy(x => x.ParentId);
                var parents = list.Where(x => string.IsNullOrWhiteSpace(x.ParentId)).OrderBy(x => x.Orderby);
                orderByList.AddRange(parents);
                foreach (var item in parents)
                {
                    foreach (var group in groups)
                    {
                        if (group.Any(x => x.ParentId == item.MenuId))
                        {
                            orderByList.AddRange(group.OrderBy(x => x.Orderby));
                        }
                    }
                }
                return orderByList;
            }
            return list;
        }

        public static MenuSetting Get(string id, string xmlUrl)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = Common.LoadXml<MenuSetting>(xmlUrl);
            return list.FirstOrDefault(x => x.MenuId == id);
        }

        public static void InsertMenuSetting(MenuSetting item, string xmlUrl)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = Common.LoadXml<MenuSetting>(xmlUrl);
            if (string.IsNullOrWhiteSpace(item.ParentId))
            {
                if (list.Where(x => string.IsNullOrWhiteSpace(x.ParentId)).Count() >= 3)
                {
                    throw new Exception("最多可创建3个一级菜单");
                }
            }
            else
            {
                if (!list.Any(x => x.MenuId == item.MenuId) && list.Where(x => x.ParentId == item.ParentId).Count() >= 5)
                {
                    throw new Exception("最多可创建5个二级菜单");
                }
            }
            var searchItem = list.FirstOrDefault(x => x.MenuId == item.MenuId && x.ParentId == item.ParentId);
            if (list.Count() > 0 && searchItem != null)
            {
                searchItem = item;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(item.ParentId))
                {
                    var parentItem = list.FirstOrDefault(x => x.MenuId == item.ParentId);
                    parentItem.MenuType = 0;
                    parentItem.MenuKey = string.Empty;
                    parentItem.MenuUrl = string.Empty;
                }
                var orderbyList = list.Where(x => x.ParentId == item.ParentId);
                if (orderbyList.Count() == 0)
                {
                    item.Orderby = 1;
                }
                else
                {
                    var maxIndex = orderbyList.Max(x => x.Orderby) + 1;
                    var obItem = orderbyList.FirstOrDefault(x => x.Orderby == item.Orderby);
                    if (obItem != null)
                    {
                        item.Orderby = obItem.Orderby;
                        obItem.Orderby = maxIndex;
                    }
                    else
                    {
                        item.Orderby = item.Orderby >= maxIndex || item.Orderby <= 0 ? maxIndex : item.Orderby;
                    }
                }

                list.Add(item);
            }
            Common.SaveXml<MenuSetting>(xmlUrl, list, false);
        }

        public static void UpdateMenuSetting(MenuSetting item, string xmlUrl)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = Common.LoadXml<MenuSetting>(xmlUrl);
            var updateItem = list.FirstOrDefault(x => x.MenuId == item.MenuId);
            if (updateItem != null)
            {

                updateItem.MenuName = string.IsNullOrWhiteSpace(item.MenuName) ? updateItem.MenuName : item.MenuName;
                switch (item.MenuType)
                {
                    case 1://Click
                        if (string.IsNullOrWhiteSpace(updateItem.ParentId))
                        {
                            list.RemoveAll(x => string.Equals(x.ParentId, updateItem.MenuId));
                        }
                        updateItem.MenuUrl = "";
                        updateItem.MenuKey = item.MenuKey;
                        updateItem.MenuType = item.MenuType;
                        break;
                    case 2://View
                        if (string.IsNullOrWhiteSpace(updateItem.ParentId))
                        {
                            list.RemoveAll(x => string.Equals(x.ParentId, updateItem.MenuId));
                        }
                        updateItem.MenuUrl = item.MenuUrl;
                        updateItem.MenuType = item.MenuType;
                        updateItem.MenuKey = "";
                        break;
                    default:
                        updateItem.MenuType = 0;
                        break;
                }
                if (!string.Equals(updateItem.ParentId, item.ParentId))
                {
                    if (string.IsNullOrWhiteSpace(item.ParentId))
                    {
                        if (list.Where(x => string.IsNullOrWhiteSpace(x.ParentId)).Count() >= 3)
                        {
                            throw new Exception("最多可创建3个一级菜单");
                        }
                    }
                    else
                    {
                        if (list.Count(x => x.ParentId == item.ParentId) >= 5)
                        {
                            throw new Exception("最多可创建5个二级菜单");
                        }
                    }
                    var tempParentId = updateItem.ParentId;
                    updateItem.ParentId = item.ParentId;
                    updateItem.Orderby = item.Orderby;
                    var tempList = list.Where(x => x.ParentId == item.ParentId).OrderBy(x => x.Orderby).ToList();
                    for (int i = 0; i < tempList.Count(); i++)
                    {
                        tempList[i].Orderby = i + 1;
                    }
                    var maxOrder = tempList.Count();
                    var obItem = tempList.FirstOrDefault(x => x.Orderby == item.Orderby);
                    if (obItem != null && updateItem.MenuId != obItem.MenuId)
                    {
                        var tempIndex = updateItem.Orderby;
                        updateItem.Orderby = obItem.Orderby;
                        obItem.Orderby = item.Orderby > maxOrder ? maxOrder + 1 : tempIndex;
                    }
                    var oldList = list.Where(x => x.ParentId == tempParentId).OrderBy(x => x.Orderby).ToList();
                    for (int i = 0; i < oldList.Count(); i++)
                    {
                        oldList[i].Orderby = i + 1;
                    }
                }
                else
                {
                    updateItem.Orderby = item.Orderby;
                    var orderbyList = list.Where(x => x.ParentId == updateItem.ParentId).OrderBy(x => x.Orderby).ToList();
                    if (orderbyList.Count() > 0)
                    {
                        for (int i = 0; i < orderbyList.Count(); i++)
                        {
                            orderbyList[i].Orderby = i + 1;
                        }
                        var maxOrder = orderbyList.Max(x => x.Orderby);
                        var obItem = orderbyList.FirstOrDefault(x => x.Orderby == item.Orderby);
                        if (obItem != null && updateItem.MenuId != obItem.MenuId)
                        {
                            var tempIndex = updateItem.Orderby;
                            updateItem.Orderby = obItem.Orderby;
                            obItem.Orderby = item.Orderby > maxOrder ? maxOrder + 1 : tempIndex;
                        }
                    }
                }
                updateItem.ModifyTime = DateTime.Now;
            }
            Common.SaveXml<MenuSetting>(xmlUrl, list, false);
        }

        public static void DeleteMenuSetting(string menuId, string xmlUrl)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = Common.LoadXml<MenuSetting>(xmlUrl);
            var delItem = list.FirstOrDefault(x => x.MenuId == menuId);
            if (delItem != null)
            {
                if (string.IsNullOrWhiteSpace(delItem.ParentId))
                {//如果是一级菜单，则删除对应二级菜单
                    list.RemoveAll(x => x.MenuId == delItem.MenuId || x.ParentId == delItem.MenuId);
                }
                else
                {//如果是二级菜单，直接移除
                    list.Remove(delItem);
                }
            }
            var orderList = list.Where(x => x.ParentId == delItem.ParentId).OrderBy(x => x.Orderby).ToList();
            for (int i = 0; i < orderList.Count(); i++)
            {//重新排序
                orderList[i].Orderby = i + 1;
            }
            Common.SaveXml<MenuSetting>(xmlUrl, list);
        }

        public static void UpdateMenuSetting(List<MenuSetting> list, string xmlUrl)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            Common.SaveXml<MenuSetting>(xmlUrl, list);
        }

        /// <summary>
        /// 发布微信菜单
        /// </summary>
        /// <param name="xmlUrl"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string PublishWechatMenu(string xmlUrl, string accessToken)
        {
            if (!File.Exists(xmlUrl))
            {
                throw new Exception("不存在菜单文件设置文件");
            }
            var list = GetAll(xmlUrl);
            return WechatAPI.PublishWechatMenu(accessToken, list);
        }
    }
}
